package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	TencentCloud "duoke/utils/tencent_cloud"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"time"
)

var TencentIm = new(tencentImService)

type tencentImService struct{}

func (s *tencentImService) BindUser(c *gin.Context, bindId int) (*[]model.AccountImportRequest, error) {
	const userIdPrefix = "zmkj_"

	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}

	if user.Id == bindId {
		return nil, errors.New("不能绑定自己")
	}

	tx := orm.Db.NewSession()
	tx.Begin()
	defer tx.Rollback()

	// 检查 bindId 用户是否存在
	count, err := tx.Where("id = ?", bindId).Count(new(tables.User))
	if err != nil {
		return nil, err
	}
	if count == 0 {
		return nil, errors.New("该用户不存在")
	}

	userIds := []int{user.Id, bindId}

	// 查询不在 im_user 表中的用户
	var users []tables.User
	err = tx.Table("user").
		In("id", userIds).
		And("NOT EXISTS (SELECT 1 FROM im_user WHERE im_user.user_id = user.id)").
		Find(&users)
	if err != nil {
		return nil, err
	}

	var account []model.AccountImportRequest
	var imUsers []tables.ImUser

	if len(users) == 0 {
		// 所有用户都已存在于 im_user 表中
		err = tx.In("user_id", userIds).Find(&imUsers)
		if err != nil {
			return nil, err
		}
		for _, item := range imUsers {
			account = append(account, model.AccountImportRequest{
				UserId:   item.ImUserId,
				Nickname: item.Nickname,
				FaceUrl:  item.FaceUrl,
			})
		}
		return &account, nil
	}

	// 构建 AccountImportRequest 并准备插入 im_user 表
	for _, item := range users {
		imUserId := userIdPrefix + gconv.String(item.Id)
		account = append(account, model.AccountImportRequest{
			UserId:   imUserId,
			Nickname: item.Nickname,
			FaceUrl:  item.Avatar,
		})
		imUsers = append(imUsers, tables.ImUser{
			UserId:   item.Id,
			Nickname: item.Nickname,
			FaceUrl:  item.Avatar,
			ImUserId: imUserId,
		})
	}

	// 请求腾讯 IM 接口
	param, err := TencentCloud.SetParam(&model.ParamsIm{
		Url: "v4/im_open_login_svc/multiaccount_import",
	})
	if err != nil {
		return nil, err
	}
	requests := model.AccountImportRequests{AccountList: &account}
	accountImport, err := TencentCloud.TencentImUtils.SendIMRequest(param, &requests)
	if err != nil {
		return nil, err
	}

	var resp model.ResponseIm
	if err = json.Unmarshal(accountImport, &resp); err != nil {
		return nil, err
	}
	if resp.ActionStatus == "FAIL" {
		return nil, errors.New("IM服务调用失败：" + resp.ErrorInfo)
	}

	// 插入 im_user 数据
	_, err = tx.Table("im_user").InsertMulti(&imUsers)
	if err != nil {
		return nil, err
	}

	if err = tx.Commit(); err != nil {
		return nil, err
	}

	return &account, nil
}
func (s *tencentImService) SendMsg(c *gin.Context, req *model.SendFromMsgRequest) error {
	const userIdPrefix = "zmkj_"
	user, err := Request.User(c)
	if err != nil {
		return err
	}
	fromId := userIdPrefix + gconv.String(user.Id)

	// 验证用户是否存在于 im_user 表中
	var imUsers []tables.ImUser
	err = orm.Db.In("im_user_id", []string{fromId, req.ToUserId}).Find(&imUsers)
	if err != nil {
		return err
	}
	if len(imUsers) != 2 {
		return errors.New("用户未注册IM服务")
	}

	// 查询目标用户在线状态
	param, err := TencentCloud.SetParam(&model.ParamsIm{
		Url: "v4/openim/query_online_status",
	})
	if err != nil {
		return err
	}

	statusResp, err := TencentCloud.TencentImUtils.SendIMRequest(param,
		&model.OnlineStatusRequest{ToAccount: []string{fromId, req.ToUserId}})
	if err != nil {
		return err
	}
	var OnlineStatusResponse model.OnlineStatusResponse
	err = json.Unmarshal(statusResp, &OnlineStatusResponse)
	if err != nil {
		return err
	}
	state := 0
	for _, item := range OnlineStatusResponse.QueryResult {
		if item.ToAccount == req.ToUserId && item.Status == "Online" {
			state = 1
		}
	}
	// 根据在线状态发送消息
	msgRandom := rand.Intn(1000000) // 扩大随机范围减少重复概率
	sendReq := &model.SendMsgRequest{
		FromAccount: fromId,
		ToAccount:   req.ToUserId,
		MsgRandom:   msgRandom,
		MsgBody: []model.MsgBodyItem{
			{
				MsgType: "TIMTextElem",
				MsgContent: model.TextMsgContent{
					Text: req.Content,
				},
			},
		},
	}

	// 根据在线状态发送消息
	var url string
	if state == 1 {
		url = "v4/openim/sendmsg"
	} else {
		url = "v4/openim/sendmsg"
		// 离线消息同步设置
		sendReq.OfflinePushInfo = &model.OfflinePush{
			PushFlag: 0,
			Desc:     "离线推送内容",
			Ext:      "这是透传内容",
			Android:  &model.AndroidPush{Sound: "shake"},
		}
	}

	param, err = TencentCloud.SetParam(&model.ParamsIm{Url: url})
	if err != nil {
		return err
	}

	resp, err := TencentCloud.TencentImUtils.SendIMRequest(param, sendReq)
	if err != nil {
		return err
	}
	var SendMsgResponse model.SendMsgResponse
	err = json.Unmarshal(resp, &SendMsgResponse)
	if err != nil {
		return err
	}
	return nil
}
func (s *tencentImService) AdminGeotropism(c *gin.Context, req *model.AdminGeotropismReq) (*model.AdminGeotropismRsp, error) {
	const userIdPrefix = "zmkj_"
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	userId := userIdPrefix + gconv.String(user.Id)
	var imUsers tables.ImUser
	get, err := orm.Db.Where("im_user_id=?", userId).Get(&imUsers)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("用户错误")
	}
	// 拉取用户历史聊天记录
	// 查询目标用户在线状态
	param, err := TencentCloud.SetParam(&model.ParamsIm{
		Url: "v4/openim/admin_getroammsg",
	})
	now := time.Now()
	// 获取当前时间

	unix := now.Unix()
	// 计算两年前的时间
	var MaxTime int

	twoYearsAgo := now.AddDate(-2, 0, 0).Unix()
	if req.MaxTime == 0 {
		MaxTime = int(unix)
	} else {
		MaxTime = req.MaxTime
	}
	adminGeotropism := model.AdminGeotropismReq{
		OperatorAccount: userId,
		PeerAccount:     req.PeerAccount,
		MaxCnt:          15,
		MinTime:         int(twoYearsAgo),
		MaxTime:         MaxTime,
	}
	if req.LastMsgKey != "" {
		adminGeotropism.LastMsgKey = req.LastMsgKey
	}
	resp, err := TencentCloud.TencentImUtils.SendIMRequest(param, &adminGeotropism)
	if err != nil {
		return nil, err
	}
	var rsp model.AdminGeotropismRsp
	err = json.Unmarshal(resp, &rsp)
	if err != nil {
		return nil, err
	}
	return &rsp, nil
}
func (s *tencentImService) DeleteMsg(c *gin.Context, req *model.DeleteMsgReq) error {
	const userIdPrefix = "zmkj_"
	user, err := Request.User(c)
	if err != nil {
		return err
	}
	userId := userIdPrefix + gconv.String(user.Id)
	msgReq := model.DeleteImMsgReq{
		OperatorAccount: userId,
		PeerAccount:     req.ToUserId,
		MsgKeyList:      req.MsgKeyList,
	}
	// 查询目标用户在线状态
	param, err := TencentCloud.SetParam(&model.ParamsIm{
		Url: "v4/openim/delete_c2c_msg_ramble",
	})
	if err != nil {
		return err
	}
	request, err := TencentCloud.TencentImUtils.SendIMRequest(param, &msgReq)
	if err != nil {
		return err
	}
	var imRsp model.ResponseIm
	if err = json.Unmarshal(request, &imRsp); err != nil {
		return err
	}
	if imRsp.ActionStatus == "FAIL" {
		return errors.New(imRsp.ErrorInfo)
	}
	return nil
}

func (s *tencentImService) AdminMsgWithdrawReq(c *gin.Context, req *model.AdminMsgWithdrawReq) error {
	const userIdPrefix = "zmkj_"
	user, err := Request.User(c)
	if err != nil {
		return fmt.Errorf("删除消息错误：%s", err.Error())
	}
	userId := userIdPrefix + gconv.String(user.Id)
	// 构建撤回消息构造数据
	msgReq := model.AdminMsgWithdrawSendReq{
		FromAccount: userId,
		ToAccount:   req.ToUserId,
		MsgKey:      req.MsgKey,
	}
	// 查询目标用户在线状态
	param, err := TencentCloud.SetParam(&model.ParamsIm{
		Url: "v4/openim/admin_msgwithdraw",
	})
	if err != nil {
		return err
	}
	request, err := TencentCloud.TencentImUtils.SendIMRequest(param, &msgReq)
	if err != nil {
		return fmt.Errorf("删除消息错误：%s", err.Error())
	}
	var imRsp model.ResponseIm
	if err = json.Unmarshal(request, &imRsp); err != nil {
		return err
	}
	if imRsp.ActionStatus == "FAIL" {
		return errors.New(imRsp.ErrorInfo)
	}
	return nil
}
func (s *tencentImService) CallbackBeforeSendMsg(req *model.CallbackBeforeSendMsgReq) {

}
